﻿Imports System.Printing
Imports System.Management
Imports System.Net

Namespace Coding4Fun.PrinterDisplayHack
	Public Class LocalPrinter
		Public Property Name() As String
		Public Property PortName() As String
		Public Property Address() As IPAddress
	End Class

	Public Class PrinterUtils
		Public Shared Function GetPrinters() As List(Of LocalPrinter)
			Dim ports As Dictionary(Of String, IPAddress) = GetPrinterPorts()

			Dim enumerationFlags() As EnumeratedPrintQueueTypes = { EnumeratedPrintQueueTypes.Local }

			Dim printServer As New LocalPrintServer()

			Dim printQueuesOnLocalServer As PrintQueueCollection = printServer.GetPrintQueues(enumerationFlags)

			Return ( _
			    From printer In printQueuesOnLocalServer _
			    Where ports.ContainsKey(printer.QueuePort.Name) _
			    Select New LocalPrinter() With {.Name = printer.Name, .PortName = printer.QueuePort.Name, .Address = ports(printer.QueuePort.Name)}).ToList()
		End Function

		Public Shared Function GetPrinterPorts() As Dictionary(Of String, IPAddress)
			Dim ports = New Dictionary(Of String, IPAddress)()

			Dim oquery As New ObjectQuery("Select Name, HostAddress from Win32_TCPIPPrinterPort where PortNumber = 9100")

			Dim mosearcher As New ManagementObjectSearcher(oquery)

			Using searcher = New ManagementObjectSearcher(oquery)
				Dim objectCollection = searcher.Get()

				For Each managementObjectCollection As ManagementObject In objectCollection
					Dim portAddress = IPAddress.Parse(managementObjectCollection.GetPropertyValue("HostAddress").ToString())
					ports.Add(managementObjectCollection.GetPropertyValue("Name").ToString(), portAddress)
				Next managementObjectCollection
			End Using

			Return ports
		End Function
	End Class
End Namespace
